import Panel from "./../../elements/Panel";
import Header from "./../../components/Header";
import Modal from "./../../components/Modal/";
import {connect} from "react-redux";
import CONFIG from "./../../libs/config";
import {Lang} from "./../../libs/";
import {URL, setTitle} from "./../../libs/Url";
import Fetch from "./../../libs/fetch";
import Label from "./../../components/FormLabel";
import FormGroup from "./../../components/FormGroup";
import FormItem from "./../../components/FormItem";
import FormItemType from "./../../components/FormItemType";
import InputGroup from "./../../components/InputGroup";
import Selected from "./../../components/SelectItem";
import BreadcrumbNavigation from "./../../components/BreadcrumbNavigation";
import {fetch, setArgumentItem} from "../../actions";
import {SUBJECT, PAGE_SUBJECT} from "./../../actions/subject";


const AddNews = React.createClass({
    getInitialState(){

        const self = this;
        this.isUpdate = this.props.router.params.id;
        setTitle(this.isUpdate ? Lang.title.update_class_honour : Lang.title.new_class_honour);
        return {
            open: false,
            selected: '',
            form: [
                {
                    name: 'type',
                    label: '荣誉类别',
                    value: 'class',
                    tips: '',
                    required: true,
                    inits: [],
                    type: FormItemType.SELECT,
                    onchange: function (index, content) {
                        self.setState({
                            form: [
                                ...self.state.form.slice(0, index),
                                Object.assign({}, self.state.form[index], {
                                    value: content,
                                    tips: content.length ? '' : '该项必填',
                                }),
                                ...self.state.form.slice(index + 1),
                            ]
                        });
                    }
                },
                {
                    name: 'id',
                    label: '获奖者',
                    value: '',
                    tips: '',
                    required: true,
                    inits: [],
                    type: FormItemType.SELECT,
                    onchange: function (index, content) {
                        self.setState({
                            form: [
                                ...self.state.form.slice(0, index),
                                Object.assign({}, self.state.form[index], {
                                    value: content,
                                    tips: content.length ? '' : '该项必填',
                                }),
                                ...self.state.form.slice(index + 1),
                            ]
                        });
                    }
                },
                {
                    name: 'name',
                    label: '荣誉名称',
                    placeholder: '',
                    required: true,
                    value: '',
                    tips: '',
                    type: FormItemType.INPUT,
                    onchange: function (index, content) {
                        self.setState({
                            form: [
                                ...self.state.form.slice(0, index),
                                Object.assign({}, self.state.form[index], {
                                    value: content,
                                    tips: content.length ? '' : '该项必填',
                                }),
                                ...self.state.form.slice(index + 1),
                            ]
                        });
                    }
                },

                {
                    name: 'fileids',
                    label: '图片',
                    value: '',
                    required: true,
                    placeholder: '',
                    tips: '',
                    type: FormItemType.UPLOAD,
                    onchange: function (index, content) {
                        self.setState({
                            form: [
                                ...self.state.form.slice(0, index),
                                Object.assign({}, self.state.form[index], {
                                    value: content,
                                    tips: content.length ? '' : '该项必填',
                                }),
                                ...self.state.form.slice(index + 1),
                            ]
                        });
                    }
                },

                {
                    name: 'summary',
                    label: '简介',
                    value: '',
                    required: true,
                    type: FormItemType.TEXT_AREA,
                    placeholder: '',
                    tips: '',
                    onchange: function (index, content) {
                        self.setState({
                            form: [
                                ...self.state.form.slice(0, index),
                                Object.assign({}, self.state.form[index], {
                                    value: content,
                                    tips: content.length ? '' : '该项必填',
                                }),
                                ...self.state.form.slice(index + 1),
                            ]
                        });
                    }
                }
            ],
            tips: {},
            ['class']: [],
            ['teacher']: [],
            ['student']: [],
            opt: {['class']: [], teacher: [], student: []},//荣誉选项对应群体{['荣誉名称']:[]}
        }
    },
    setchange(index, content){
        const self = this;
        self.setState({
            form: [
                ...self.state.form.slice(0, index),
                Object.assign({}, self.state.form[index], {
                    value: content,
                    tips: content.length ? '' : '该项必填',
                }),
                ...self.state.form.slice(index + 1),
            ]
        })
    },
    componentDidMount() {
        const {dispatch} = this.props;
        var request = [
            Fetch(URL.Get_USER_CLASS),
            Fetch(URL.CLASS_HONOUR_TEACHER_STUDENT),
            Fetch(URL.CLASS_STUDENT_FIND),
        ];
        if (this.isUpdate) {
            request.push(Fetch(URL.CLASS_HONOUR_GET, {body: {honerid: this.isUpdate}}))
        }
        Promise.all(request)
            .then(res=> {
                var state = {
                    ['class']: res[0].list,
                    ['teacher']: res[1].list,
                    ['student']: res[2].list,
                };
                var form = this.state.form;
                if (this.isUpdate) {
                    var honour = state.honour = res[3].honer;
                    form[0].value = honour.type;
                    form[1].value = honour[honour.type + 'id'];
                    form[2].value = honour['name'];
                    form[3].value = honour['fileids'];
                    form[4].value = honour['content'];
                    state.form = form;
                    console.log(state.form)
                }
                this.setState(state);
            })
            .catch(e=> {
                console.log(e);
            });
    },
    componentWillReceiveProps(nextProps){
        const self = this;
    },
    onsubmit(){
        const {dispatch} = this.props;
        const self = this;
        var form = {};
        self.state.form.forEach((item, index)=> {
            if (item.required && item.value.length == 0) {
                if (index == 1) {
                    var value_ = self.state.form[0].value == 'class' ? self.state['class'][0].classid : (
                        self.state.form[0].value == 'teacher' ? (self.state['teacher'][0].teacherid) : self.state['student'][0].studentid
                    );
                    form[item.name] = value_;
                } else {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                tips: '该项必填',
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    })
                }

            } else {
                form[item.name] = item.value
            }
        });
        if (Object.keys(form).length == self.state.form.length) {
            form.url = URL.CLASS_HONOUR_ADD;
            form[this.refs['type'].value + 'id'] = form['id'];
            if (this.isUpdate) {
                form['honerid'] = this.isUpdate;
            }
            Fetch(this.isUpdate ? URL.CLASS_HONOUR_MODIFY : URL.CLASS_HONOUR_ADD, {body: form})
                .then(res=> {
                    console.log(res);
                    alert('保存成功!');
                    if (!this.isUpdate) {
                        self.props.router.push(CONFIG.MENUS_ABSOLUTE.CLASS_HONOUR)
                    }
                })
                .catch(e=> {
                    console.log(e);
                    alert('保存失败!')
                });
        }
    },
    render(){
        const self = this;
        const {dispatch, user} = this.props, state = this.state;
        const arguments_ = self.props[PAGE_SUBJECT.CLASS_HONOUR_ADD].arguments || {type: 'class'};
        console.log(user['class']);
        return (
            <div>
                <BreadcrumbNavigation navs={[
                    {url: CONFIG.MENUS.HOME, label: '首页'},
                    {url: CONFIG.MENUS_ABSOLUTE.CLASS_HONOUR, label: '班级荣誉'},
                    {label: this.isUpdate ? '荣誉编辑' : '新建荣誉'},
                ]}>
                </BreadcrumbNavigation>
                <Panel>
                    <Header>{this.isUpdate ? '荣誉编辑' : '新建荣誉'}</Header>
                    <div className="form-horizontal">
                        {
                            self.state.form.map((item, index)=> {
                                if (item.type == FormItemType.SELECT) {
                                    return <FormItem {...item} key={index}>
                                        <select
                                            ref={item.name}
                                            className="form-control"
                                            onChange={(e)=> {
                                                if (item.label != '获奖者') {

                                                }
                                                item.onchange(index, e.target.value);
                                            }}>
                                            {
                                                (item.label == '荣誉类别') && CONFIG.HONOUR_TYPE.map(function (item_, index) {
                                                    var selected = false;
                                                    if (item_.type == item.value) {
                                                        selected = true;
                                                    }
                                                    return <option defaultValue={item_.type}
                                                                   selected={selected}
                                                                   value={item_.type}
                                                                   key={index}>{item_.label}</option>
                                                })
                                            }
                                            {
                                                (self.state.form[0].value != 'class' && item.label == '获奖者' ) ?
                                                    state[[state.form[0].value]]
                                                        .map((item_, index)=> {
                                                            var value_ = state.form[0].value == 'class' ? item_['class'].classid : (
                                                                state.form[0].value == 'teacher' ? (item_.teacherid) : item_.studentid
                                                            );
                                                            var name = state.form[0].value == 'class' ? item_['class'].name : (
                                                                state.form[0].value == 'teacher' ? (item_.name) : item_.name
                                                            );
                                                            var selected = false;
                                                            if (value_ == item.value) {
                                                                selected = true;
                                                            }
                                                            return <option selected={selected} value={value_}
                                                                           key={index}>{name}</option>
                                                        }) : ''
                                            }
                                        </select>
                                    </FormItem>
                                }
                                else {
                                    return <FormItem index={index} {...item}
                                                     key={index}></FormItem>
                                }
                            })
                        }
                        <FormGroup>
                            <Label></Label>
                            <InputGroup>
                                <button onClick={self.onsubmit} className="btn btn-success"
                                        type="submit">
                                    保存
                                </button>
                            </InputGroup>
                        </FormGroup>
                    </div>
                </Panel>
            </
                div >
        )
    }
});
function select(state) {
    console.log(state.user)
    return {
        user: state.user.user,
        // [SUBJECT.CLASS_HONOUR_ADD]: state.fetchBySubject[SUBJECT.CLASS_HONOUR_ADD],
        [PAGE_SUBJECT.CLASS_HONOUR_ADD]: state.pageBySubject[PAGE_SUBJECT.CLASS_HONOUR_ADD]
    }
}
export default connect(select)(AddNews)